package com.atguigu.gmall.pms.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.mapper.CategoryMapper;
import com.atguigu.gmall.pms.entity.CategoryEntity;
import com.atguigu.gmall.pms.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, CategoryEntity> implements CategoryService {

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<CategoryEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public List<CategoryEntity> parent(Long parentId) {
        LambdaQueryWrapper<CategoryEntity> queryWrapper =
                Wrappers.lambdaQuery(CategoryEntity.class);
        //parentId = -1 表示查询所有
        //其他值表示当做父id查询
        if(parentId !=-1){
            //  select * from pms_category where parent_id = 0;
            queryWrapper.eq(CategoryEntity::getParentId,parentId);
        }
        //ServiceImpl查询数据时 底层通过Mapper查询：
        return this.list(queryWrapper);
    }

    @Override
    public List<CategoryEntity> subs(Long parentId) {
        //CategoryEntity： 前端页面需要调用对象的subs属性 获取 二级的三级分类列表
        //自定义sql实现：
        return baseMapper.selectSubsByParentId(parentId);
    }

    @Override
    public List<CategoryEntity> hasSubs() {
        //先查询parent_id=0的 一级分类
        List<CategoryEntity> levelOneCates = this.parent(0L);
        //遍历查询一级分类的下一级分类：如果为空 设置一级分类没有下一级 否则设置有下一级
        levelOneCates.forEach(categoryEntity -> {
            List<CategoryEntity> levelTwoCates = this.parent(categoryEntity.getId());
            categoryEntity.setChildren(CollectionUtils.isEmpty(levelTwoCates)?false:true);
        });

        return levelOneCates;
    }

    @Override
    public List<CategoryEntity> queryLevel123cates(Long c3id) {
        CategoryEntity c3 = this.getById(c3id);
        if(c3==null){
            return null;
        }
        Long c2id = c3.getParentId();
        CategoryEntity c2 = this.getById(c2id);
        Long c1id = c2.getParentId();
        CategoryEntity c1 = this.getById(c1id);
        //页面遍历展示分类集合： 从索引0位置先获取一级分类展示
        return Arrays.asList(c1,c2,c3);
    }

}